<script setup>

import Card from "@/components/Card.vue";
import {Message, Notebook, Refresh, Select} from "@element-plus/icons-vue";

import {useStore} from "@/store";
import {computed, onMounted, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import {post, get, accessHeader} from "@/net";
import axios from "axios";


const store = useStore();
const registerTime = computed(() => new Date(store.user.registerTime).toLocaleString());
const baseFormRef = ref()
const emailFormRef = ref()
const desc = ref('')
const loading = reactive({
  form: true,
  base: false
})

const baseForm = reactive({
  username: '',
  gender: '0',
  phone: '',
  qq: '',
  wx: '',
  desc: ''
})

const emailForm = reactive({
  email: '',
  code: ''
})

const validateUsername = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("请输入用户名"))
  } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
    callback(new Error("用户名不能包含特殊字符，只能是中文/英文"))
  } else {
    callback()
  }
}

const rules = {
  username: [
    {validator: validateUsername, trigger: ['blur', 'change']},
    {min: 2, max: 10, message: '用户名长度需要在2~10个字符', trigger: ['blur', 'change']}
  ],
  email: [
    {required: true, message: '请输入邮件地址', trigger: ['blur', 'change']},
    {type: 'email', message: '请输入合法的电子邮件', trigger: ['blur', 'change']}
  ],
  code: [
    {required: true, message: '请获取验证码', trigger: ['blur', 'change']}
  ]
}

const saveDetails = () => {
  baseFormRef.value.validate(isValid => {
    if (isValid) {
      loading.base = true
      post('api/user/save-details', baseForm, () => {
        ElMessage.success('用户信息保存成功')
        store.user.username = baseForm.username
        desc.value = baseForm.desc
        loading.base = false
      }, () => {
        ElMessage.warning('用户信息保存失败')
        loading.base = false
      })
    }
  })
}

// getUserInfo = () =>{
//
// }
get('api/user/details', data => {
  console.log(data)
  baseForm.username = store.user.username
  baseForm.gender = data.gender
  baseForm.phone = data.phone
  baseForm.qq = data.qq
  baseForm.wx = data.wx
  baseForm.desc = desc.value = data.desc
  emailForm.email = store.user.email
  loading.form = false
})

const codeTime = ref(0)
const isValidEmail = ref(true)
const onValidate = (prop, isValid) => {
  if (prop === 'email') {
    isValidEmail.value = isValid
  }
}
const sendEmailCode = () => {
  codeTime.value = 60
  emailFormRef.value.validate(isValid => {
    if (isValid) {
      get(`api/auth/ask-code?email=${emailForm.email}&type=modify`, () => {
        ElMessage.success(`验证码已发送至您的邮箱: ${emailForm.email},请注意查收！`)
        let timer = setInterval(() => {
          codeTime.value--
          if (codeTime.value === 0) {
            clearInterval(timer)
          }
        }, 1000)
      }, (message) => {
        ElMessage.warning(message)
        codeTime.value = 0
      })
    }
  })
}

const modifyEmail = () => {
  emailFormRef.value.validate(isValid => {
    if (isValid) {
      post('/api/user/modify-email', emailForm, () => {
        ElMessage.success('邮箱修改成功')
        store.user.email = emailForm.email
        codeTime.value = 0
      })
    }
  })
}

const beforeUpload = (file) => {
  if (file.type != 'image/jpeg' && file.type != 'image/png') {
    ElMessage.warning('只能上传PNG/JPEG图片')
    return false
  } else if (file.size / 1024 > 1024) {
    ElMessage.warning('图片大小不能超过1M')
    return false
  } else {
    return true
  }
}

const uploadSuccess = (res) => {
  ElMessage.success('头像上传成功')
  store.user.avatar = res.data
}
// onMounted(()=>{
//
// })
</script>

<template>
  <div style="display: flex;max-width: 950px;margin: auto">
    <div class="settings-left">
      <card :icon="Notebook" title="账号信息设置"
            description="在这里编辑您的个人信息，您可以在隐私设置中选择是否展示这些信息" v-loading="loading.form">
        <el-form :model="baseForm" :rules="rules" ref="baseFormRef" label-position="top"
                 style="margin:0 10px 20px 10px ">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="baseForm.username" maxlength="10"/>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="baseForm.gender">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="baseForm.phone" maxlength="11"/>
          </el-form-item>
          <el-form-item label="QQ号" prop="qq">
            <el-input v-model="baseForm.qq" maxlength="11"/>
          </el-form-item>
          <el-form-item label="微信号" prop="wx">
            <el-input v-model="baseForm.wx" maxlength="20"/>
          </el-form-item>
          <el-form-item label="个人简介" prop="desc">
            <el-input v-model="baseForm.desc" type="textarea" :rows="6" maxlength="200"/>
          </el-form-item>
        </el-form>
        <el-button type="success" @click="saveDetails()" :loading="loading.base">
          <el-icon style="margin-right: 3px"><Select/></el-icon>
          保存用户信息
        </el-button>
      </card>
      <card style="margin-top: 10px;" :icon="Message" title="电子邮件设置"
            description="您可以在这里更改默认的电子邮件地址">
        <el-form :model="emailForm" @validate="onValidate" :rules="rules" ref="emailFormRef" label-position="top"
                 style="margin:0 10px 20px 10px ">
          <el-form-item label="电子邮件地址" prop="email">
            <el-input v-model="emailForm.email"/>
          </el-form-item>
          <el-form-item prop="code">
            <el-row style="width: 100%" :gutter="10">
              <el-col :span="18">
                <el-input placeholder="请获取验证码" v-model="emailForm.code" maxlength="6"/>
              </el-col>
              <el-col :span="6">
                <el-button type="success" style="width: 100%" plain @click="sendEmailCode()"
                           :disabled="!isValidEmail || codeTime>0">
                  {{ codeTime > 0 ? `请稍候${codeTime} 秒` : '获取验证码' }}
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <el-button type="success" @click="modifyEmail()">
          <el-icon style="margin-right: 3px">
            <Refresh/>
          </el-icon>
          更新电子邮件地址
        </el-button>
      </card>
    </div>
    <div class="settings-right">
      <div style="position: sticky;top: 20px">
        <card>
          <div style="text-align: center;padding: 5px 15px 0 15px;">
            <el-avatar size="70" :src="store.getAvatarURL"/>
            <div style="margin: 5px 0">
              <el-upload :action="axios.defaults.baseURL + '/api/image/avatar'"
                         :show-file-list="false"
                         :before-upload="beforeUpload"
                         :on-success="uploadSuccess"
                         :headers="accessHeader()">
                <el-button size="small" round >上传头像</el-button>
              </el-upload>
            </div>
            <div style="font-weight: bold">您好,{{ store.user.username }}</div>
            <el-divider style="margin: 10px 0"/>
            <div style="font-size: 14px;color: grey;padding: 10px">
              {{ desc }}
            </div>
          </div>
        </card>
        <card style="margin-top: 10px; font-size: 14px">
          <div>账号注册时间：{{ registerTime }}</div>
          <div style="color: gray">欢迎加入我们的学习论坛！</div>
        </card>
      </div>

    </div>

  </div>

</template>

<style scoped>
.settings-left {
  flex: 1;
  margin: 20px;
}

.settings-right {
  width: 300px;
  margin: 20px 30px 20px 0;
}
</style>